package org.example.netty.demo.chapter4;

import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.SimpleChannelInboundHandler;
import org.example.netty.demo.common.Cmd;

import java.lang.reflect.Method;
import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;

/**
 * @author ： minzhiwei
 * create by 2020/1/19 20:18
 * @description
 */
public class InvokeHandler extends SimpleChannelInboundHandler<Cmd> {
    private final Map<Method, Object> objectTable = new ConcurrentHashMap<>();
    /**
     * Is called for each message of type {@link Cmd}.
     *
     * @param ctx the {@link ChannelHandlerContext} which this {@link SimpleChannelInboundHandler}
     *            belongs to
     * @param msg the message to handle
     * @throws Exception is thrown if an error occurred
     */
    @Override
    protected void channelRead0(ChannelHandlerContext ctx, Cmd msg) throws Exception {
        Object o = objectTable.get(msg.getMethod());
        if(o == null) {
            o = msg.getClazz().newInstance();
            objectTable.putIfAbsent(msg.getMethod(),o);
        }
        msg.getMethod().invoke(o, msg.getArgs());
    }
}
